C#中常用加密算法
【转载:http://www.cnblogs.com/Continue/archive/2009/11/20/1606862.html】
在日常的项目开发中,很多时候都会用到加密/解密的功能,以下是我整理出来的一些常见加密/解密的算法:包括MD5加密、SHA256加密、移位加密/解密、DES加密/解密、AES加密/解密,给大家分享一下。
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; public class Encrypt { MD5加密#region MD5加密 /**//// <summary> /// MD5加密算法 /// </summary> /// <param name="PassWord">待加密的字符串</param> /// <returns>加密后的字符串</returns> public static string MD5Encrypt(string Input) { byte[] b = Encoding.Default.GetBytes(Input); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } /**//// <summary> /// MD5加密 /// </summary> /// <param name="Half">加密是16位还是32位;如果为true为16位</param> /// <param name="Input">待加密码字符串</param> /// <returns>加密后的字符串</returns> public static string MD5Encrypt(string Input, bool Half) { string output = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Input, "MD5").ToLower(); if (Half)//16位MD5加密(取32位加密的9~25字符) output = output.Substring(8, 16); return output; } #endregion SHA256加密#region SHA256加密 /**//// <summary> /// SHA256加密 /// </summary> /// /// <param name="str">待加密的字符串</param> /// <returns>加密后的字符串</returns> public static string SHAEncrypt(string str) { byte[] SHA256Data = Encoding.UTF8.GetBytes(str); SHA256Managed Sha256 = new SHA256Managed(); byte[] Result = Sha256.ComputeHash(SHA256Data); return Convert.ToBase64String(Result); //返回长度为44字节的字符串 } #endregion 移位加密/解密#region 移位加密/解密 /**//// <summary> /// 字符串移位加密 /// </summary> /// <param name="str">待加密数据</param> /// <returns>加密后的数据</returns> public static string ShiftEncrypt(string Input) { try { string _temp = ""; int _inttemp; char[] _chartemp = Input.ToCharArray(); for (int i = 0; i < _chartemp.Length; i++) { _inttemp = _chartemp[i] + 1; _chartemp[i] = (char)_inttemp; _temp += _chartemp[i]; } return _temp; } catch { return Input.ToString(); } } /**//// <summary> /// 字符串移位解密 /// </summary> /// <param name="str">待解密数据</param> /// <returns>解密成功后的数据</returns> public static string ShiftDecrypt(string Input) { try { string _temp = ""; int _inttemp; char[] _chartemp = Input.ToCharArray(); for (int i = 0; i < _chartemp.Length; i++) { _inttemp = _chartemp[i] - 1; _chartemp[i] = (char)_inttemp; _temp += _chartemp[i]; } return _temp; } catch { return Input.ToString(); } } #endregion DES加密/解密#region DES加密/解密 /**//// <summary> /// DES加密 /// </summary> /// <param name="Text">待加密的字符串</param> /// <returns>加密后的字符串</returns> public static string DESEncrypt(string Text) { return DESEncrypt(Text, "Continue"); } /**//// <summary> /// DES加密 /// </summary> /// <param name="Text">待加密的字符串</param> /// <param name="sKey">加密密钥</param> /// <returns>加密后的字符串</returns> public static string DESEncrypt(string Text, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray = Encoding.Default.GetBytes(Text); des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } return ret.ToString(); } /**//// <summary> /// DES解密 /// </summary> /// <param name="Text">待解密的字符串</param> /// <returns>解密后的字符串</returns> public static string DESDecrypt(string Text) { return DESDecrypt(Text, "Continue"); } /**//// <summary> /// DES解密 /// </summary> /// <param name="Text">待解密的字符串</param> /// <param name="sKey">解密密钥</param> /// <returns>解密后的字符串</returns> public static string DESDecrypt(string Text, string sKey) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len; len = Text.Length / 2; byte[] inputByteArray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } catch { return ""; } } #endregion AES加密/解密#region AES加密/解密 //默认密钥向量 private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F }; /**//// <summary> /// AES加密 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥</param> /// <returns>加密后的字符串</returns> public static string AESEncrypt(string encryptString, string encryptKey) { encryptKey = GetSubString(encryptKey, 0, 32, ""); encryptKey = encryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor(); byte[] inputData = Encoding.UTF8.GetBytes(encryptString); byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Convert.ToBase64String(encryptedData); } /**//// <summary> /// AES加密 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <returns>加密后的字符串</returns> public static string AESEncrypt(string encryptString) { return AESEncrypt(encryptString, "Continue"); } /**//// <summary> /// AES解密 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥</param> /// <returns>解密后的字符串</returns> public static string AESDecrypt(string decryptString, string decryptKey) { try { decryptKey = GetSubString(decryptKey, 0, 32, ""); decryptKey = decryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor(); byte[] inputData = Convert.FromBase64String(decryptString); byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Encoding.UTF8.GetString(decryptedData); } catch { return ""; } } /**//// <summary> /// AES解密 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <returns>解密后的字符串</returns> public static string AESDecrypt(string decryptString) { return AESDecrypt(decryptString, "Continue"); } /**//// <summary> /// 取指定长度的字符串 /// </summary> /// <param name="p_SrcString">要检查的字符串</param> /// <param name="p_StartIndex">起始位置</param> /// <param name="p_Length">指定长度</param> /// <param name="p_TailString">用于替换的字符串</param> /// <returns>截取后的字符串</returns> private static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString) { string myResult = p_SrcString; Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString); foreach (char c in Encoding.UTF8.GetChars(bComments)) { //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3) if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3')) { //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+")) //当截取的起始位置超出字段串长度时 if (p_StartIndex >= p_SrcString.Length) return ""; else return p_SrcString.Substring(p_StartIndex, ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length); } } if (p_Length >= 0) { byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString); //当字符串长度大于起始位置 if (bsSrcString.Length > p_StartIndex) { int p_EndIndex = bsSrcString.Length; //当要截取的长度在字符串的有效长度范围内 if (bsSrcString.Length > (p_StartIndex + p_Length)) { p_EndIndex = p_Length + p_StartIndex; } else { //当不在有效范围内时,只取到字符串的结尾 p_Length = bsSrcString.Length - p_StartIndex; p_TailString = ""; } int nRealLength = p_Length; int[] anResultFlag = new int[p_Length]; byte[] bsResult = null; int nFlag = 0; for (int i = p_StartIndex; i < p_EndIndex; i++) { if (bsSrcString[i] > 127) { nFlag++; if (nFlag == 3) nFlag = 1; } else nFlag = 0; anResultFlag[i] = nFlag; } if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1)) nRealLength = p_Length + 1; bsResult = new byte[nRealLength]; Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength); myResult = Encoding.Default.GetString(bsResult); myResult = myResult + p_TailString; } } return myResult; } #endregion }
这里是上面的源代码:点击这里下载
注:
“b[i].ToString("x").PadLeft(2, '0');”
byte转十六进制直接ToString("X2")就可以了。